package com.hua.store.web.servlet;

import com.hua.store.domin.Orders;
import com.hua.store.service.OrderService;
import com.hua.store.service.impl.OrderServiceImpl;
import net.sf.json.JSONArray;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

@WebServlet(name = "AdminOrderServlet", urlPatterns = "/AdminOrderServlet")
public class AdminOrderServlet extends BaseServlet {

    public String findAllOrder(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
        String state = req.getParameter("state");
        List<Orders> list = null;
        OrderService service = new OrderServiceImpl();
        if (state == null || "".equals(state)) {
            list = service.findAllOrder();
        } else {
            list = service.findAllOrder(state);
        }
        req.setAttribute("allOrders", list);
        return "/admin/order/list.jsp";
    }

    //findOrderWithAjax
    public String findOrderWithAjax(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String oid = req.getParameter("oid");
        OrderService service = new OrderServiceImpl();
        Orders order = service.findOrderByOid(oid);
        JSONArray jsonOrderItem = JSONArray.fromObject(order.getList());
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().println(jsonOrderItem);
        return null;
    }

    //changeOrderState
    public String changeOrderState(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String oid = req.getParameter("oid");
        OrderService service = new OrderServiceImpl();
        Orders order = service.findOrderByOid(oid);
        service.updateOrder(order);
        resp.sendRedirect("/admin/order/list.jsp");
        return null;
    }
}
